Power of Two
LeetCode 231 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2^x.
Example 1:
Input: n = 1
Output: true
Explanation: 2^0 = 1
Example 2:
Input: n = 16
Output: true
Explanation: 2^4 = 16
Example 3:
Input: n = 3
Output: false
Constraints:
- `-2^31 <= n <= 2^31 - 1`
Follow up: Could you solve it without loops/recursion?
Topics: Math, Bit Manipulation, Recursion
Approachβ
Bit Manipulationβ
Operate directly on binary representations. Key operations: AND (&), OR (|), XOR (^), NOT (~), shifts (<<, >>). XOR is especially useful: a ^ a = 0, a ^ 0 = a.
Finding unique elements, power of 2 checks, subset generation, toggling flags.
Mathematicalβ
Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.
Problems with clear mathematical structure, counting, number properties.
Solutionsβ
Solution 1: C# (Best: 44 ms)β
| Metric | Value |
|---|---|
| Runtime | 44 ms |
| Memory | N/A |
| Date | 2018-04-12 |
public class Solution {
public bool IsPowerOfTwo(int n) {
if(n<=0) return false;
var x = n & n-1;
return x==0;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Bit Manipulation | $O(n) or O(1)$ | $O(1)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.